package com.design.pattern.flyweight;

import java.util.HashMap;
import java.util.Map;

/**
 * 非共享汽车类
 */
public class CarUnSharedConcreteFlyWeight implements CarFlyWeight {
    private static HashMap<Class<?>, Map<Object, CarFlyWeight>> cars = new HashMap<>();

    public void add(CarFlyWeight car) {
        Map<Object, CarFlyWeight> tmpCars = cars.get(car.getClass());
        if (null==tmpCars){
            tmpCars=new HashMap<>();
        }
        if (car instanceof BigCarConcreteFlyWeight) {
            //以轮子做分类
            CarFlyWeight
                    bigCar = tmpCars.size()==0?null:tmpCars.get(((BigCarConcreteFlyWeight) car).getWheels());

            if (null == bigCar) {
                bigCar=BigCarFlyWeightFactory.get(((BigCarConcreteFlyWeight) car).getWheels());
                if (null==bigCar){
                    BigCarFlyWeightFactory.add((BigCarConcreteFlyWeight) car);
                }
                tmpCars.put(((BigCarConcreteFlyWeight) car).getWheels(), car);
                cars.put(car.getClass(), tmpCars);
            }
        } else if (car instanceof LittleConcreteFlyWeight) {
            CarFlyWeight little = tmpCars.size()==0?null:tmpCars.get(((LittleConcreteFlyWeight) car).getColor());
            if (null == little) {
                little= LittleCarFlyWeightFactory.get(((LittleConcreteFlyWeight) car).getColor());
                if (null==little){
                    LittleCarFlyWeightFactory.add((LittleConcreteFlyWeight) car);
                }
                //颜色做分类
                tmpCars.put(((LittleConcreteFlyWeight) car).getColor(), car);
                cars.put(car.getClass(), tmpCars);
            }
        }


    }

    public void remove(CarFlyWeight car) {
        Map<Object, CarFlyWeight> tmpCars = cars.get(car.getClass());
        if (car instanceof BigCarConcreteFlyWeight) {
            //以轮子做分类
            tmpCars.put(((BigCarConcreteFlyWeight) car).getWheels(), car);
            cars.remove(car.getClass(), tmpCars);
        } else if (car instanceof LittleConcreteFlyWeight) {
            //颜色做分类
            ((LittleConcreteFlyWeight) car).getColor();
            tmpCars.remove(((LittleConcreteFlyWeight) car).getColor(), car);
        }
    }

    @Override
    public void display(Coordinate coordinate) {
        for (Map<Object, CarFlyWeight> cars2 : cars.values()) {
            for (CarFlyWeight carFlyWeight : cars2.values()) {
                carFlyWeight.display(coordinate);
            }
        }
    }
}
